package xdu.ble.auth.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xdu.ble.auth.client.UserClient;
import xdu.ble.auth.config.JwtProperties;
import xdu.ble.common.enums.ExceptionCode;
import xdu.ble.common.exception.BLEException;
import xdu.ble.user.entity.Admin;
import xdu.lz.auth.entity.UserInfo;
import xdu.lz.auth.utils.JwtUtils;


@Service
@Slf4j
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties properties;


    private final Logger logger = LoggerFactory.getLogger(AuthService.class);
    /**
     * 用户授权
     */
    public String authentication(String phoneNum, String passWord) {
        try{
            //1.调用微服务查询用户信息
            Admin admin = this.userClient.login(phoneNum, passWord);
            logger.debug("auth--- admin = " + admin);
            //2.查询结果为空，则用户信息不匹配，其实上面已经抛异常了，在queryUser里面已经处理null了
            if (admin == null){
                throw new BLEException(ExceptionCode.PHONE_OR_PASSWORD_ERROR);
            }
            //3.查询结果不为空，则生成token
            String token = JwtUtils.generateToken(new UserInfo(admin.getId(), admin.getUserName(),phoneNum),
                    properties.getPrivateKey(), properties.getExpire());
            return token;
        }catch (Exception e){
            log.error("【鉴权中心】用户名或密码错误,phoneNum:{}",phoneNum,e);
            throw new BLEException(ExceptionCode.PHONE_OR_PASSWORD_ERROR);
        }
    }


}
